package com.bigfans.orderservice.ordertracker;

import com.lmax.disruptor.LiteBlockingWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.*;

public class ExpiredOrderTracker {

    private BlockingQueue<ExpiredOrderTrack> orderQueue = new LinkedBlockingQueue();
    private volatile boolean loop = true;

    private Disruptor<ExpiredOrderTrack> disruptor;
    private ExecutorService executor;

    public void startTrack(){
        executor = Executors.newCachedThreadPool();
        int bufferSize = 1024;
//        disruptor = new Disruptor<>(new ExpiredOrderTrackFactory() , bufferSize , executor,
//                ProducerType.SINGLE , new LiteBlockingWaitStrategy());
        disruptor.handleEventsWith(new ExpiredOrderTrackHandler());
        disruptor.start();

        RingBuffer<ExpiredOrderTrack> ringBuffer = disruptor.getRingBuffer();

        while (loop) {
            ExpiredOrderTrack track = orderQueue.peek();
            if(track.hasExpired()){

                continue;
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void track(ExpiredOrderTrack orderTrack){
        orderQueue.offer(orderTrack);
    }

    public void stopTrack(){
        loop = false;
        if(disruptor != null){
            disruptor.shutdown();
        }
        if(executor != null && !executor.isShutdown()){
            executor.shutdown();
        }
    }
}
